package com.gzsxy.esjy.sign.socket;

import com.alibaba.fastjson.JSON;
import com.gzsxy.esjy.sign.InnerSignCode;
import com.gzsxy.esjy.sign.async.AsyncWsClient;
import com.gzsxy.esjy.sign.cache.SignCacheManager;
import com.gzsxy.esjy.sign.dto.BaseSignProtocolDto;
import com.gzsxy.esjy.sign.dto.InnerSignDto;
import com.gzsxy.esjy.sign.service.GSSignBusinessService;
import com.gzsxy.esjy.sign.service.GSSignService;
import com.gzsxy.esjy.sign.util.SignProtocolUtil;
import io.netty.handler.timeout.IdleStateEvent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 投屏板 websocket 消息
 * @author zhangxiaolong
 * @since 2022/7/15
 */
@Slf4j
@Component
public class ScreenAsyncWsCallBack implements AsyncWsCallBack {

    @Autowired
    private SignCacheManager cacheManager;

    @Autowired
    private GSSignBusinessService gsSignBusinessService;

    @Autowired
    private GSSignService gsSignService;

    @Override
    public void doResponse(AsyncWsClient asyncWsClient, Object msg) {
        log.info("接收到消息：{}", JSON.toJSONString(msg));
    }

    @Override
    public void connected(AsyncWsClient asyncWsClient) {
        InnerSignDto innerSignDto = getSignDto(asyncWsClient, "与签名板连接成功", InnerSignCode.CONNECTED_CODE);
        gsSignBusinessService.deviceStatus(innerSignDto);
    }

    @Override
    public void disConnected(AsyncWsClient asyncWsClient) {
        if (cacheManager.getSignTaskCache().containsKey(asyncWsClient.getRequestId())) {
            BaseSignProtocolDto cancelSign = SignProtocolUtil.getCancelSignByType(asyncWsClient.getRequestId(), asyncWsClient.getDevType()
                    , gsSignBusinessService.getSignOkUrl());
            gsSignService.cancelSign(asyncWsClient.getIp(), asyncWsClient.getPort(), cancelSign);
            //睡一下，等待消息处理
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
            }
            cacheManager.clearSignByRequestId(asyncWsClient.getRequestId(), true, true);
        }
        InnerSignDto innerSignDto = getSignDto(asyncWsClient, "与签名板连接断开", InnerSignCode.DISCONNECT_ERROR_CODE);
        gsSignBusinessService.deviceStatus(innerSignDto);
    }

    @Override
    public void exception(AsyncWsClient asyncWsClient, Throwable cause) {
        InnerSignDto innerSignDto = getSignDto(asyncWsClient, "与签名板连接异常断开：" + cause.getMessage(), InnerSignCode.EX_DISCONNECT_ERROR_CODE);
        gsSignBusinessService.deviceStatus(innerSignDto);
    }

    @Override
    public void heartbeat(AsyncWsClient asyncWsClient, IdleStateEvent event) {

    }
}
